use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::sync::Mutex;
use tauri::Manager;

/// 应用配置结构
#[derive(Serialize, Deserialize, Clone)]
pub struct AppConfig {
    pub shortcut: ShortcutConfig,
    pub screenshot: ScreenshotConfig,
    pub translate: TranslateConfig,
}

/// 截图配置
#[derive(Serialize, Deserialize, Clone)]
pub struct ScreenshotConfig {
    pub border_radius: f64,
}

/// 快捷键配置
#[derive(Serialize, Deserialize, Clone)]
pub struct ShortcutConfig {
    pub translate: String,
    pub screenshot: String,
    pub setting: String,
}

/// 翻译配置
#[derive(Serialize, Deserialize, Clone)]
pub struct TranslateConfig {
    pub auto_close: bool,
}

/// 应用配置存储状态
pub struct AppConfigStore {
    pub cfg: Mutex<AppConfig>,
}

impl AppConfig {
    /// 创建默认配置
    pub fn default() -> Self {
        Self {
            shortcut: ShortcutConfig {
                translate: if cfg!(target_os = "macos") {
                    "Cmd+Shift+T".into()
                } else {
                    "Ctrl+Shift+T".into()
                },
                screenshot: if cfg!(target_os = "macos") {
                    "Cmd+Shift+S".into()
                } else {
                    "Ctrl+Shift+S".into()
                },
                setting: if cfg!(target_os = "macos") {
                    "Cmd+,".into()
                } else {
                    "Ctrl+,".into()
                },
            },
            screenshot: ScreenshotConfig {
                border_radius: 0.0,
            },
            translate: TranslateConfig {
                auto_close: false,
            },
        }
    }
}

/// 获取配置文件路径
pub fn get_config_file_path(app: &tauri::AppHandle) -> Option<PathBuf> {
    let dir = app.path().app_config_dir().ok()?;
    Some(dir.join("config.json"))
}

/// 加载配置
pub fn load_config(app: &tauri::AppHandle) -> Option<AppConfig> {
    let path = get_config_file_path(app)?;
    let data = fs::read_to_string(path).ok()?;
    serde_json::from_str::<AppConfig>(&data).ok()
}

/// 保存配置
pub fn save_config(app: &tauri::AppHandle, cfg: &AppConfig) -> Result<(), String> {
    let path = get_config_file_path(app).ok_or_else(|| "配置路径不可用".to_string())?;
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    let data = serde_json::to_string_pretty(cfg).map_err(|e| e.to_string())?;
    fs::write(path, data).map_err(|e| e.to_string())
}

/// Tauri 命令：获取应用配置
#[tauri::command]
pub fn get_app_config(state: tauri::State<AppConfigStore>) -> AppConfig {
    state.cfg.lock().unwrap().clone()
}

// Tauri 命令：设置应用配置
#[tauri::command]
pub fn set_app_config(app: tauri::AppHandle, state: tauri::State<AppConfigStore>, new_cfg: AppConfig) -> Result<(), String> {
    {
        let mut cfg_lock = state.cfg.lock().unwrap();
        *cfg_lock = new_cfg;
    }
    save_config(&app, &state.cfg.lock().unwrap()).map_err(|e| e.to_string())?;
    Ok(())
}

/// Tauri 命令：获取截图配置
#[tauri::command]
pub fn get_screenshot_config(state: tauri::State<AppConfigStore>) -> ScreenshotConfig {
    state.cfg.lock().unwrap().screenshot.clone()
}

/// Tauri 命令：设置截图配置
#[tauri::command]
pub fn set_screenshot_config(
    app: tauri::AppHandle,
    state: tauri::State<AppConfigStore>,
    border_radius: f64,
) -> Result<(), String> {
    {
        let mut cfg = state.cfg.lock().unwrap();
        cfg.screenshot.border_radius = border_radius;
    }
    save_config(&app, &state.cfg.lock().unwrap()).map_err(|e| e.to_string())?;
    Ok(())
}

